package com.sxfq.loansupermarket.backsystem.modular.doctorLooked.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.sxfq.loansupermarket.backsystem.common.constant.factory.PageFactory;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.common.exception.BizExceptionEnum;
import com.sxfq.loansupermarket.backsystem.common.exception.BussinessException;
import com.sxfq.loansupermarket.backsystem.common.persistence.model.Dept;
import com.sxfq.loansupermarket.backsystem.common.persistence.model.User;
import com.sxfq.loansupermarket.backsystem.core.log.LogManager;
import com.sxfq.loansupermarket.backsystem.core.log.factory.LogTaskFactory;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.DateTimeKit;
import com.sxfq.loansupermarket.backsystem.core.support.HttpKit;
import com.sxfq.loansupermarket.backsystem.core.util.DateUtil;
import com.sxfq.loansupermarket.backsystem.core.util.StringUtil;
import com.sxfq.loansupermarket.backsystem.core.util.ToolUtil;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.CustomerInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.ReturnVisitInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.SearchReturnVisitInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.service.ICustomerService;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.basicData.entity.PayServiceInfo;
import com.sxfq.loansupermarket.backsystem.modular.doctorLooked.entity.*;
import com.sxfq.loansupermarket.backsystem.modular.doctorLooked.service.IDoctorLookedService;
import com.sxfq.loansupermarket.backsystem.modular.marketing.entity.ReservationsInfo;
import com.sxfq.loansupermarket.backsystem.modular.marketing.service.IReservationsService;
import com.sxfq.loansupermarket.backsystem.modular.refunds.entity.RechargeInfo;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.entity.AddVisitedInfo;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.entity.ConsultantInfo;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.service.IConsultantService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Case;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 医生看诊
 *
 * @author py
 * @Date 2018年4月19日23:15:54
 */
@Controller
@RequestMapping("/doctorLooked")
public class DoctorLookedController extends BaseController {

    @Autowired
    IDoctorLookedService service;


    @Autowired
    IConsultantService consultantService;

    @Autowired
    ICustomerService customerService;


    @Autowired
    IReservationsService reservationsService;

    @Autowired
    private SqlMapper sqlMapper;

    private String PREFIX = "/doctorLooked/";

    /**
     * 跳转到医生看诊
     */
    @RequestMapping("")
    public String consultant(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("user", ShiroKit.getUser().getAccount());
        return PREFIX + "/new_doctor_looked.html";
    }

    /**
     * 跳转到医生回访
     */
    @RequestMapping("/doctor_visit")
    public String doctor_visit(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        return PREFIX + "doctor_revisit.html";
    }

    /**
     * 跳转到医生划价预览界面
     */
    @RequestMapping("/charge_price")
    public String doctorChangePrice(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        return PREFIX + "doctor_charge_price.html";
    }

    /**
     * 跳转到医生收费明细
     */
    @RequestMapping("/doctor_appointment/{cid}")
    public String doctor_appointment(@PathVariable String cid, Model model) {
        String customerId = cid.split(",")[0];
        String reservationsId = cid.split(",")[1];
        String doctor = cid.split(",")[2];
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String sql = "select * from " + this.getTableName() + " where id='" + customerId + "' " +
                " and reservations_id='" + reservationsId + "'";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        model.addAttribute("doctor", doctor);
        model.addAttribute("customerInfo", customerInfo);
        return PREFIX + "doctor_appointment.html";
    }

    /**
     * 跳转到医生收费明细
     */
    @RequestMapping("/doctor_appointments/{cid}")
    public String doctor_appointments(@PathVariable String cid, Model model) {
        String customerId = cid.split(",")[0];
        String reservationsId = cid.split(",")[1];
        String doctor = cid.split(",")[2];
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String sql = "select * from " + this.getTableName() + " where id='" + customerId + "' " +
                " and reservations_id='" + reservationsId + "'";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        model.addAttribute("doctor", doctor);
        model.addAttribute("customerInfo", customerInfo);
        return PREFIX + "doctor_appointments.html";
    }

    /**
     * 就诊记录 修改 跳转页面
     */
    @RequestMapping("/doctor_update_appointment/{cid}")
    public String doctorUpdateAppointment(@PathVariable String cid, Model model) {
        String customerId = cid.split(",")[0];
        String reservationsId = cid.split(",")[1];
        String doctor = cid.split(",")[2];
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String sql = "select * from " + this.getTableName() + " where id='" + customerId + "' " +
                " and reservations_id='" + reservationsId + "'";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        model.addAttribute("doctor", doctor);
        model.addAttribute("customerInfo", customerInfo);
        return PREFIX + "doctor_update_appointment.html";
    }


    /**
     * 统计医生收费金额
     */
    @RequestMapping(value = "/totalMoney", method = RequestMethod.GET)
    @ResponseBody
    public double totalMoney(String payServiceName, String startTime, String endTime) throws Exception {
        String sqltj = "";
        if (StringUtils.isNotBlank(startTime)) {
            sqltj += " and  t.operation_time >= '" + startTime + "' ";
        }
        if (StringUtils.isNotBlank(endTime)) {
            sqltj += " and  t.operation_time <= '" + endTime + "' ";
        }
        if (StringUtils.isNotBlank(payServiceName)) {
            sqltj += " and  t1.pay_service_name like CONCAT('%" + payServiceName + "%') ";
        }
        String sql2 = "select * from user a left join role b on a.roleId=b.id where a.account='" + ShiroKit.getUser().getAccount() + "'";
        User user = sqlMapper.selectOne(sql2, User.class);
        if (user != null) {
            if ("1".equals(user.getRoleid()) || "1,".equals(user.getRoleid().substring(0, 2))) {
                sqltj += " ";
            } else {
                sqltj += " and t.doctor = '" + ShiroKit.getUser().getAccount() + "' ";
            }
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String tableName1 = tableHead + "deal_info";
        String sql = "select sum(t4.serviceActualPay) serviceActualPay from( select sum(t3.serviceActualPay) as serviceActualPay, sum(t3.foldingPay) as foldingPay,t3.id,t3.id2,t3.doctor, t3.payServiceName,sum(t3.payServiceNum) as payServiceNum\n" +
                " from  (select sum(t.service_actual_pay) as serviceActualPay, t.folding_pay as foldingPay ,t.id as id, t.id2 as id2,t.doctor as doctor,\n" +
                " t1.pay_service_name as payServiceName,t.pay_service_num as payServiceNum,t.pay_service_id as payServiceId from " + tableName1 + " t left join pay_service_info t1 on t.pay_service_id=t1.id\n" +
                " left join " + this.getTableName() + " t2 on t.customer_id=t2.id\n" +
                " where t.deal_status='已成交'\n" + sqltj +
                " group by t.id2\n" +
                "  order by t.operation_time) t3 group by t3.payServiceId ) t4";
        PayServiceInfo searchInfo = sqlMapper.selectOne(sql, PayServiceInfo.class);
        return searchInfo.getServiceActualPay();
    }


    /**
     * 跳转到医生排班
     */
    @RequestMapping("/doctor_scheduling")
    public String doctor_scheduling(Model model) {

        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        return PREFIX + "doctor_scheduling.html";
    }

    /**
     * 跳转到医生排班
     */
    @RequestMapping("/doctor_preview")
    public String doctor_preview(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        return PREFIX + "doctor_preview.html";
    }

    /**
     * 跳转到预约客户
     */
    @RequestMapping("/doctor_addTask/{eventData}")
    public String doctor_addTask(@PathVariable String eventData, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String startTime = eventData.split(",")[0];
        String endTime = eventData.split(",")[1];
        String doctor = eventData.split(",")[2];
        String continued = eventData.split(",")[3];
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("startTime", startTime);
        model.addAttribute("endTime", endTime);
        model.addAttribute("doctor", doctor);
        model.addAttribute("continued", continued);
        return PREFIX + "doctor_addTask.html";
    }

    /**
     * 跳转到修改预约客户
     */
    @RequestMapping("/doctor_addTasks/{ids}")
    public String doctor_addTasks(@PathVariable String ids, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String sql = "select left(t.start_time,19) as startTime,t.* from " + this.getTableName() + " t where  (t.customer_status !='作废'  or t.customer_status is null ) and t.id='" + ids + "' ";
        ConsultantInfo consultantInfo = sqlMapper.selectOne(sql, ConsultantInfo.class);
        if (StringUtil.isNotEmpty(consultantInfo.getAppointmentPayService())) {
            String payService = consultantInfo.getAppointmentPayService().substring(0, consultantInfo.getAppointmentPayService().length() - 1);
            model.addAttribute("payService", payService);
        } else {
            model.addAttribute("payService", "");
        }
        model.addAttribute("consultantInfo", consultantInfo);
        model.addAttribute("customerId", ids);
        return PREFIX + "doctor_addTasks.html";
    }


    /**
     * 通过 ID 查看预约患者信息
     */
    @RequestMapping("/doctor_display/{sid}")
    public String doctor_display(@PathVariable String sid, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String startTime = sid.split(",")[0];
        String id = sid.split(",")[1];
        String endTime = sid.split(",")[2];
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String sql = "select * from " + this.getTableName() + " t" +
                " where t.customer_status!='作废' and t.id='" + id + "' ";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        model.addAttribute("startTime", startTime);
        model.addAttribute("endTime", endTime);
        model.addAttribute("customerInfo", customerInfo);
        return PREFIX + "doctor_display.html";
    }


    /**
     * 跳转到医生收费明细
     */
    @RequestMapping("/charge_schedule")
    public String charge_schedule(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        return PREFIX + "charge_schedule.html";
    }

    /**
     * 医生划价预览表格
     */
    @RequestMapping("/getDoctorChargePrice")
    @ResponseBody
    public Object getDoctorChargePrice(SearchDoctorLookedInfo info, HttpServletRequest request) {
        Page<DoctorLookedInfo> page = new PageFactory<DoctorLookedInfo>().defaultPage();
        try {
            List<DoctorLookedInfo> list = service.selectDoctorChargePrice(page, info);
            page.setRecords(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.packForBT(page);
    }

    /**
     * 跳转到打印信息shortMessage
     */
    @RequestMapping("/printingAppointment/{customerId}")
    public String printingAppointment(@PathVariable String customerId, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }

        String sql = " select id as id,reservations_id as reservationsId, medical_record_number as medicalRecordNumber,medical_reasons as medicalReasons,select_reasons as selectReasons,yellow_number as yellowNumber, " +
                " arrival_store as arrivalStore,customer_name as customerName,customer_age as customerAge,occupation as occupation,one_medium as oneMedium ,two_medium as twoMedium,thr_medium as thrMedium, " +
                "one_channel as oneChannel,two_channel as twoChannel ,thr_channel as thrChannel," +
                "  email as email , wechat_number as wechatNumber ,region as region ,doctor as doctor , " +
                "country as country ,province as province, cities as cities ,archiving as archiving ,remarks as remarks ,start_time as startTime ,end_time as endTime,left(create_appointment_time,19) as createAppointmentTime," +
                "customer_phone as customerPhone ,if(customer_sex=1,'男','女') as sex  from " + this.getTableName() + " where id='" + customerId + "'";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        model.addAttribute("customerInfo", customerInfo);
        model.addAttribute("customerId", customerId);
        return PREFIX + "printingAppointment.html";
    }


    /**
     * 跳转到发送短信
     */
    @RequestMapping("/shortMessage/{customerId}")
    public String shortMessage(@PathVariable String customerId, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("customerId", customerId);
        return PREFIX + "shortMessage.html";
    }

    /**
     * 得到医生收费明细
     */
    @RequestMapping("/getChargeSchedule")
    @ResponseBody
    public Object getChargeSchedule(SearchDoctorLookedInfo info, HttpServletRequest request) {
        Page<DoctorLookedInfo> page = new PageFactory<DoctorLookedInfo>().defaultPage();
        try {
            List<DoctorLookedInfo> list = service.selectChargeSchedule(page, info);
            page.setRecords(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.packForBT(page);
    }

    /**
     * 导出数据
     *
     * @return
     */
    @RequestMapping(value = "/chargeScheduleExport")
    public void chargeScheduleExport(
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(required = false) String payServiceName, HttpServletResponse response) {
        try {
            SearchDoctorLookedInfo info = new SearchDoctorLookedInfo();
            info.setStartTime(startTime);
            info.setEndTime(endTime);
            info.setPayServiceName(payServiceName);
            List<DoctorLookedInfo> list = service.chargeScheduleExportt(info);
            // 解析成excel文件
            // 第一步，创建一个webbook，对应一个Excel文件
            HSSFWorkbook wb = new HSSFWorkbook();
            // 第二步，在wb中添加一个sheet,对应Excel文件中的sheet
            HSSFSheet sheet = wb.createSheet("前端导出");
//            if("1".equals(pageType)){
            for (int i = 0; i < 5; i++) {
                sheet.setColumnWidth(i, 24 * 256);
            }
            // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
            HSSFRow row = sheet.createRow(0);
            // 第四步，创建单元格，并设置值表头 设置表头居中
            HSSFCellStyle style = wb.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);// 创建一个居中格式
            HSSFCell cell = row.createCell(0);
            cell.setCellValue("医生");
            cell.setCellStyle(style);
            cell = row.createCell(1);
            cell.setCellValue("项目名称");
            cell.setCellStyle(style);
            cell = row.createCell(2);
            cell.setCellValue("数量");
            cell.setCellStyle(style);
            cell = row.createCell(3);
            cell.setCellValue("折后价");
            cell.setCellStyle(style);
            cell = row.createCell(4);
            cell.setCellValue("实收金额");
            cell.setCellStyle(style);

            // 填充数据
            for (int i = 0; i < list.size(); i++) {
                DoctorLookedInfo map = list.get(i);
                row = sheet.createRow(i + 1);

                String doctor = map.getDoctor();
                payServiceName = map.getPayServiceName();
                String payServiceNum = map.getPayServiceNum();
                String serviceActualPay = map.getServiceActualPay();
                String foldingPay = map.getFoldingPay();
                String customerName = map.getCustomerName();
                String customerPhone = map.getCustomerPhone();
                String sex = "";
                int customerSex = 0;
                if (map.getCustomerSex() != null) {
                    if (map.getCustomerSex() == 1) {
                        sex = "男";
                    } else if (map.getCustomerSex() == 2) {
                        sex = "女";
                    } else {
                        sex = "未知";
                    }
                }
                int customerAge = 0;
                if (map.getCustomerAge() != null) {
                    customerAge = map.getCustomerAge();
                }
                // 第四步，创建单元格，并设置值
                for (int j = 0; j <= 5; j++) {
                    row.createCell(j).setCellStyle(style);
                }
                row.getCell(0).setCellValue(doctor);
                row.getCell(1).setCellValue(payServiceName);
                row.getCell(2).setCellValue(payServiceNum);
                row.getCell(3).setCellValue(foldingPay);
                row.getCell(4).setCellValue(serviceActualPay);
            }
            String date = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new java.util.Date());
            String filename = "data" + date + ".xls";
            response.setHeader("Content-Disposition",
                    "attachment; filename=\"" + URLEncoder.encode(filename, "UTF-8") + "\"");
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 医生划价预览导出数据
     *
     * @return
     */
    @RequestMapping(value = "/doctorChargeExport")
    public void doctorChargeExport(
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(required = false) Integer checkStatus,
            @RequestParam(required = false) String doctor,
            HttpServletResponse response) {
        try {
            SearchDoctorLookedInfo info = new SearchDoctorLookedInfo();
            info.setStartTime(startTime);
            info.setEndTime(endTime);
            info.setCheckStatus(checkStatus);
            info.setDoctor(doctor);
            List<DoctorLookedInfo> list = service.doctorChargePriceExport(info);
            // 解析成excel文件
            // 第一步，创建一个webbook，对应一个Excel文件
            HSSFWorkbook wb = new HSSFWorkbook();
            // 第二步，在wb中添加一个sheet,对应Excel文件中的sheet
            HSSFSheet sheet = wb.createSheet("前端导出");
//            if("1".equals(pageType)){
            for (int i = 0; i < 6; i++) {
                sheet.setColumnWidth(i, 24 * 256);
            }
            // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
            HSSFRow row = sheet.createRow(0);
            // 第四步，创建单元格，并设置值表头 设置表头居中
            HSSFCellStyle style = wb.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);// 创建一个居中格式
            HSSFCell cell = row.createCell(0);
            cell.setCellValue("患者姓名");
            cell.setCellStyle(style);
            cell = row.createCell(1);
            cell.setCellValue("电话");
            cell.setCellStyle(style);
            cell = row.createCell(2);
            cell.setCellValue("性别");
            cell.setCellStyle(style);
            cell = row.createCell(3);
            cell.setCellValue("医生");
            cell.setCellStyle(style);
            cell = row.createCell(4);
            cell.setCellValue("项目名称");
            cell.setCellStyle(style);
            cell = row.createCell(5);
            cell.setCellValue("划价状态");
            cell.setCellStyle(style);

            // 填充数据
            for (int i = 0; i < list.size(); i++) {
                DoctorLookedInfo map = list.get(i);
                row = sheet.createRow(i + 1);
                String payServiceName = map.getPayServiceName();
                String customerName = map.getCustomerName();
                String customerPhone = map.getCustomerPhone();
                doctor = map.getDoctor();
               // checkStatus = map.getCheckStatus();
                String sex = "";
                int customerSex = 0;
                if (map.getCustomerSex() != null) {
                    if (map.getCustomerSex() == 1) {
                        sex = "男";
                    } else if (map.getCustomerSex() == 2) {
                        sex = "女";
                    } else {
                        sex = "未知";
                    }
                }
                String s="";
                //int checkStatus =0;
                if(map.getCheckStatus() !=null){
                    if(map.getCheckStatus()==1){
                        s = "已划价";
                    }else if (map.getCheckStatus() == 2) {
                        s = "未划价";
                    }
                }
                int customerAge = 0;
                if (map.getCustomerAge() != null) {
                    customerAge = map.getCustomerAge();
                }
                // 第四步，创建单元格，并设置值
                for (int j = 0; j <= 5; j++) {
                    row.createCell(j).setCellStyle(style);
                }
                row.getCell(0).setCellValue(customerName);
                row.getCell(1).setCellValue(customerPhone);
                row.getCell(2).setCellValue(sex);
                row.getCell(3).setCellValue(doctor);
                row.getCell(4).setCellValue(payServiceName);
                row.getCell(5).setCellValue(s);
            }
            String date = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new java.util.Date());
            String filename = "data" + date + ".xls";
            response.setHeader("Content-Disposition",
                    "attachment; filename=\"" + URLEncoder.encode(filename, "UTF-8") + "\"");
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //查询病历
    @RequestMapping(value = "/getCaseData", method = RequestMethod.POST)
    @ResponseBody
    public List<CaseInfo> getArchivings(String id) throws Exception {
        String sql = "select * from  case_info t1\n" +
                " LEFT JOIN tooth_site t2 on t1.id=t2.case_id\n" +
                " where t1.id='" + id + "'";
        List<CaseInfo> list = sqlMapper.selectList(sql, CaseInfo.class);
        return list;
    }

    /**
     * 医生添加就诊记录
     */
    @RequestMapping("/doctor_editors/{cad}")
    public String doctor_editors(@PathVariable String cad, Model model) {
        String doctor = cad.split(",")[0];
        String customerId = cad.split(",")[1];
        String arrivalTime = cad.split(",")[2];

        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("customerId", customerId);
        model.addAttribute("arrivalTime", arrivalTime);
        model.addAttribute("doctor", doctor);
        return PREFIX + "doctor_editors.html";
    }

    /**
     * 修改黄页编号
     */
    @RequestMapping("/numberedModification/{yi}")
    public String numberedModification(@PathVariable String yi, Model model) {
        String customerId = yi.split(",")[0];
        String yellowNumber = yi.split(",")[1];

        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("customerId", customerId);
        model.addAttribute("yellowNumber", yellowNumber);
        return PREFIX + "doctor_numberedModification.html";
    }


    /**
     * 病历模板
     */
    @RequestMapping("/doctor_template")
    public String doctor_template(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        return PREFIX + "doctor_template.html";
    }

    /**
     * 修改保存黄页编号
     *
     * @param customerId
     * @return
     */
    @RequestMapping(value = "/updateNumber", method = RequestMethod.POST)
    @ResponseBody
    public int updateNumber(String customerId,String yellowNumber) {

        String sql = "update " + this.getTableName() + "  set yellow_number ='"+yellowNumber+"' where id = '" + customerId + "'";
        String sql1 ="select t.customer_name as customerName,t.customer_phone as customerPhone,t.yellow_number as yellowNumber,t.archiving as archiving,t.id from "+this.getTableName()+" t where id='"+customerId+"'";
        CustomerInfo info = sqlMapper.selectOne(sql1,CustomerInfo.class);
        String sq11 = "INSERT INTO yellow_number_update_log (logtype, userid,customer_name,customer_phone,single_person, createtime,succeed,classname) VALUES " +
                " ( '修改'," + ShiroKit.getUser().getId() + ", '" +info.getCustomerName()+ "', '" +info.getCustomerPhone()+ "', '" + ShiroKit.getUser().getAccount() + "','"+DateTimeKit.now()+"'," +
                "'成功','" + ShiroKit.getUser().getAccount() + " 把 " + info.getCustomerName() + " 的黄页编号:"+info.getYellowNumber()+" 修改为:"+ yellowNumber + "');";
        sqlMapper.insert(sq11);
        return sqlMapper.update(sql);
    }

    /**
     * 添加就诊记录
     *
     * @param info
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/add_record")
    @ResponseBody
    public int addRecord(@Valid DoctorRevisitInfo info, String customerId, String doctor, String diagnoseTime, String expenditureProject, String diagnoseDetail, String remarks) throws Exception {

        //改变详情表状态
        String sql = "update  return_doctor_visit_info  set revisit_status= '2'  where customer_id='" + customerId + "'";
        sqlMapper.update(sql);

        String sql1 = "select * from " + this.getTableName() + " where id= '" + customerId + "'";
        DoctorDiagnosisInfo info1 = sqlMapper.selectOne(sql1, DoctorDiagnosisInfo.class);

        String sql2 = "insert into  `doctor_diagnosis_info` (`customer_id`,`reservations_id`,`doctor`,`diagnose_detail`," +
                "`diagnose_time`,pay_service_name,remarks,outpatient_name) VALUES" +
                "('" + customerId + "','" + info1.getReservationsId() + "','" + doctor + "','" + diagnoseDetail
                + "','" + diagnoseTime + "','" + expenditureProject + "','" + remarks + "','" + info1.getArrivalStore() + "');";
        return sqlMapper.insert(sql2);
    }

    /**
     * 医生完成治疗回访
     */
    @RequestMapping("/alreadyLeave/{cri}")
    public String startTreatment(@PathVariable String cri, Model model) {
        String customerId = cri.split(",")[0];
        String reservationsId = cri.split(",")[1];
        String arrivalStore = cri.split(",")[2];
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String sql2 = "update " + this.getTableName() + "  set arrival_status ='4' where id = '" + customerId + "'";
        sqlMapper.update(sql2);

        model.addAttribute("doctor", ShiroKit.getUser().getAccount());
        model.addAttribute("customerId", customerId);
        model.addAttribute("reservationsId", reservationsId);
        model.addAttribute("arrivalStore", arrivalStore);
        return PREFIX + "alreadyLeave.html";
    }


    /**
     * 点击客户 获取 患者信息 看诊记录 病例记录  成交记录  回访记录
     *
     * @param id
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/doctor_seeDiagnosis/{id}")
    public String doctor_seeDiagnosis(@PathVariable String id, Model model) throws Exception {
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        CustomerInfo customerInfo = customerService.selectOneById(id);
        //看诊详情
        List<ConsultantInfo> consultantInfoList = consultantService.getConsultantInfoList(customerInfo.getReservationsId());
        String sqlresrvations = "select * from reservations_info where id='" + customerInfo.getReservationsId() + "' limit 0,1";
        ReservationsInfo reservationsInfo = sqlMapper.selectOne(sqlresrvations, ReservationsInfo.class);
        if(reservationsInfo==null){
            String sqlcu = "select * from " + this.getTableName() + "  where id='" + id + "'";
            CustomerInfo customer = sqlMapper.selectOne(sqlcu, CustomerInfo.class);
            reservationsService.insert(customer);
            String sqlresrvations1 = "select * from reservations_info where id='" + customerInfo.getReservationsId() + "' limit 0,1";
            reservationsInfo = sqlMapper.selectOne(sqlresrvations1, ReservationsInfo.class);
        }
        String tcName = "";
        String firstVisitDate = "";
        if (customerInfo != null) {
            tcName = customerInfo.getFieldTc();
            firstVisitDate = customerInfo.getFirstVisitDate();
        }
        for (ConsultantInfo info1 : consultantInfoList) {
            if (info1.getDiagnosisTime() != "" && info1.getDiagnosisTime() != null) {
                info1.setDiagnosisTimeOne(info1.getDiagnosisTime().substring(0, 10));
                info1.setDiagnosisTimeTwo(info1.getDiagnosisTime().substring(11, info1.getDiagnosisTime().length()));
            }
        }
        //成交记录
        String tableName1 = tableHead + "deal_info";
        String sql = "select t1.id as id,t1.customer_id as customerId ,t1.reservations_id as reservationsId ,t1.outpatient_name as outpatientName , t1.deal_status  as dealStatus, t1.tc_name as tcName ,t1.pay_service_num as payServiceNum ," +
                " t1.service_actual_pay as serviceActualPay ,left(t1.operation_time,19) as operationTime,t1.remarks as remarks," +
                " t1.folding_pay as foldingPay,t1.to_void_cause as toVoidCause,t1.pay_service as payService," +
                "t2.id as payServiceId,t2.department as department,t2.first_level_project as firstLevelProject,t1.arrears as arrears," +
                "t2.pay_service_name as payServiceName, t2.pay_service_price_one as payServicePriceOne, t2.pay_service_price_two as payServicePriceTwo," +
                "t1.to_void_cause as toVoidCause ,t1.no_deal_cause as noDealCause,t1.get_time as getTime ," +
                " group_concat(t1.doctor) as doctor" +
                " from " + tableName1 + " t1 left join pay_service_info t2 on t1.pay_service_id=t2.id " +
                " where t1.reservations_id='" + customerInfo.getReservationsId() + "' and pay_service_id is not null and t1.deal_status='已成交' group by  operationTime order by operationTime desc";
        List<PayServiceInfo> payServiceInfoList = sqlMapper.selectList(sql, PayServiceInfo.class);
        String sql2 = "select t1.id as id,t1.customer_id as customerId ,t1.reservations_id as reservationsId ,t1.outpatient_name as outpatientName , t1.deal_status  as dealStatus, t1.tc_name as tcName ,t1.pay_service_num as payServiceNum ," +
                " t1.service_actual_pay as serviceActualPay ,left(t1.operation_time,19) as operationTime,t1.remarks as remarks," +
                " t1.folding_pay as foldingPay,t1.to_void_cause as toVoidCause,t1.pay_service as payService," +
                "t2.id as payServiceId,t2.department as department,t2.first_level_project as firstLevelProject,t1.arrears as arrears," +
                "t2.pay_service_name as payServiceName, t2.pay_service_price_one as payServicePriceOne, t2.pay_service_price_two as payServicePriceTwo," +
                "t1.to_void_cause as toVoidCause ,t1.no_deal_cause as noDealCause,t1.get_time as getTime ,group_concat(t1.doctor) as doctor\n" +
                " from " + tableName1 + " t1 left join pay_service_info t2 on t1.pay_service_id=t2.id " +
                " where t1.reservations_id='" + customerInfo.getReservationsId() + "' and pay_service_id is not null and t1.operation_time=t1.get_time group by  operationTime order by operationTime desc";
        List<PayServiceInfo> payServiceInfoList1 = sqlMapper.selectList(sql2, PayServiceInfo.class);
        //患者详情
        String sql1 = " select * from " + this.getTableName() + "  where id='" + id + "'";
        ConsultantInfo consultantInfo = sqlMapper.selectOne(sql1, ConsultantInfo.class);
        String getTime = "";
        if (consultantInfo != null) {
            if (consultantInfo.getCustomerSex() == 1) {
                consultantInfo.setSex("男");
            } else if (consultantInfo.getCustomerSex() == 2) {
                consultantInfo.setSex("女");
            } else {
                consultantInfo.setSex("未知");
            }
        }
        Double totleReceivable = 0.00;
        Double totleFoldingPay = 0.00;
        Double totleServiceActualPay = 0.00;
        Double accountArrears = 0.00;
        for (PayServiceInfo info1 : payServiceInfoList1) {
            if (info1 != null) {
                if (info1.getPayServiceId() != null && info1.getPayServiceId() != "") {
                    if (info1.getPayServiceNum() != null) {
                        totleReceivable += (info1.getPayServicePriceTwo()) * (info1.getPayServiceNum());
                    }
                    if (info1.getFoldingPay() != null) {
                        totleFoldingPay += info1.getFoldingPay();
                    }
                    info1.setTotleReceivable(totleReceivable);
                    info1.setTotleFoldingPay(totleFoldingPay);
                }
            }
        }
        for (PayServiceInfo info : payServiceInfoList) {
            if (info != null) {
                if (info.getPayServiceId() != null && info.getPayServiceId() != "") {
                    if (info.getServiceActualPay() != null) {
                        totleServiceActualPay += info.getServiceActualPay();
                    }
                    if (info.getArrears() != null) {
                        accountArrears += info.getArrears();
                    }
                    info.setTotleReceivable(totleReceivable);
                    info.setTotleFoldingPay(totleFoldingPay);
                    info.setTotleServiceActualPay(totleServiceActualPay);
                    info.setAccountArrears(totleServiceActualPay - totleServiceActualPay);
                }
                if (info.getOperationTime() != "" && info.getOperationTime() != null) {
                    info.setOperationTimeOne(info.getOperationTime().substring(0, 10));
                    info.setOperationTimeTwo(info.getOperationTime().substring(11, info.getOperationTime().length()));
                }
                getTime = info.getGetTime();
            }
        }
        //病例记录
        //1、先查询当前客户的所有病例记录
        String caseInfoSql = "select * from case_info t1  where t1.customer_id='" + id + "'order by t1.operation_time desc";
        List<CaseInfo> caseInfoList = sqlMapper.selectList(caseInfoSql, CaseInfo.class);

        for (CaseInfo infos : caseInfoList) {
            if (infos != null) {
                if (infos.getOperationTime() != "" && infos.getOperationTime() != null) {
                    infos.setOperationTime(infos.getOperationTime().substring(0, 10));
                }
                String sql3 = "select pay_service_name as payServiceName from pay_service_info where id ='" + infos.getPayServiceId() + "'";
                CaseInfo caseInfo1 = sqlMapper.selectOne(sql3, CaseInfo.class);
                infos.setPayServiceName(caseInfo1.getPayServiceName());
            }
        }
        //2.循环遍历每个病例记录，给对应病例的牙位属性赋值
        for (CaseInfo caseInfo : caseInfoList) {
            //然后查询牙位集合
            String toothSIteSql = "select * from tooth_site t1 where t1.case_id='" + caseInfo.getId() + "' ";
            List<ToothSite> toothSiteList = sqlMapper.selectList(toothSIteSql, ToothSite.class);
            for (ToothSite toothSite : toothSiteList) {
                //根据对应的牙位类型，给病例实体的对应牙位属性赋值
                if (toothSite.getYaType().equals("1")) {
                    caseInfo.getToothSite1List().add(toothSite);
                }
                if (toothSite.getYaType().equals("2")) {
                    caseInfo.getToothSite2List().add(toothSite);
                }
                if (toothSite.getYaType().equals("3")) {
                    caseInfo.getToothSite3List().add(toothSite);
                }
                if (toothSite.getYaType().equals("4")) {
                    caseInfo.getToothSite4List().add(toothSite);
                }
                if (toothSite.getYaType().equals("5")) {
                    caseInfo.getToothSite5List().add(toothSite);
                }
            }
        }

        //随访记录
        String sql4 = "select r.id,r.reservations_id,r.customer_id,r.revisit,r.revisit_time,r.outpatient_name,r.revisit_content,r.doctor,r.revisit_status,r.remarks  from return_doctor_visit_info r where r.reservations_id ='" + customerInfo.getReservationsId() + "' ";
        List<DoctorRevisitInfo> doctorRevisitInfo = sqlMapper.selectList(sql4, DoctorRevisitInfo.class);

        //就诊记录
        String sql5 = "select r.id,r.reservations_id,r.customer_id,r.diagnose_time,r.doctor,r.remarks,r.diagnose_detail,r.pay_service_name,w.field_tc,w.arrival_store " +
                "from doctor_diagnosis_info r left join " + this.getTableName() + " w on w.id =r.customer_id where r.reservations_id ='" + customerInfo.getReservationsId() + "' ";
        List<DoctorDiagnosisInfo> doctorDiagnosisInfo = sqlMapper.selectList(sql5, DoctorDiagnosisInfo.class);
        for (DoctorDiagnosisInfo info1 : doctorDiagnosisInfo) {
            if (info1.getDiagnoseTime() != "" && info1.getDiagnoseTime() != null) {
                info1.setDiagnoseTime(info1.getDiagnoseTime().substring(0, 19));
            }
        }
        model.addAttribute("payServiceInfoList", payServiceInfoList);
        model.addAttribute("reservationsId", customerInfo.getReservationsId());
        model.addAttribute("customerId", id);
        model.addAttribute("customerInfo", customerInfo);
        model.addAttribute("getTime", getTime);
        model.addAttribute("tcName", tcName);
        model.addAttribute("firstVisitDate", firstVisitDate);
        model.addAttribute("reservationsInfo", reservationsInfo);
        model.addAttribute("consultantInfo", consultantInfo);
        model.addAttribute("consultantInfoList", consultantInfoList);
        model.addAttribute("caseInfoList", caseInfoList);
        model.addAttribute("doctorRevisitInfo", doctorRevisitInfo);
        model.addAttribute("userName", ShiroKit.getUser().getName());
        model.addAttribute("doctorDiagnosisInfo", doctorDiagnosisInfo);
        return PREFIX + "doctor_seeDiagnosis.html";

    }

    @RequestMapping(value = "/to_doctor_comment/{id}")
    public String to_doctor_comment(@PathVariable String id, Model model) {
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        ConsultantInfo consultantInfo = this.consultantService.selectOneById(id);
        if (consultantInfo != null) {
            if (consultantInfo.getCustomerSex() == 1) {
                consultantInfo.setSex("男");
            } else if (consultantInfo.getCustomerSex() == 2) {
                consultantInfo.setSex("女");
            } else {
                consultantInfo.setSex("未知");
            }
        }
        String sql = "select * from reservations_info where id='" + consultantInfo.getReservationsId() + "' limit 0,1";
        ReservationsInfo reservationsInfo = sqlMapper.selectOne(sql, ReservationsInfo.class);
        model.addAttribute("consultantInfo", consultantInfo);
        model.addAttribute("reservationsInfo", reservationsInfo);
        model.addAttribute("reservationsId", consultantInfo.getReservationsId());
        return PREFIX + "doctor_comment.html";
    }

    @RequestMapping(value = "/doctorComment")
    @ResponseBody
    public int doctorComment(@Valid ReservationsInfo info, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        return service.doctorComment(info);
    }

    @RequestMapping(value = "/add_isRevisitd")
    @ResponseBody
    public int add_isRevisitd(@Valid CustomerInfo info, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String appointmentTime = "";
        if (info.getAppointmentTime() == null || info.getAppointmentTime() == "") {
            appointmentTime = "null";
        } else {
            appointmentTime = "'" + info.getAppointmentTime() + "'";
        }
        if (info.getRevisitContent() == null || info.getRevisitContent() == "") {
            String sql = "update " + this.getTableName() + " set cause_of_no_return_visit='" + info.getCauseOfNoReturnVisit() + "',is_return_visit=" + info.getIsReturnVisit() + "," +
                    "remarks_of_return_visit='" + info.getRemarksOfReturnVisit() + "',reservations='" + info.getReservations() + "',appointment_time=" + appointmentTime + ",return_to_remark='" + ShiroKit.getUser().getAccount() + "'" +
                    " where reservations_id='" + info.getReservationsId() + "'";
            return sqlMapper.update(sql);
        } else {
//            service.updateIsReturnVisit(info);
            consultantService.insertReturnVisit(info);
            String sqlselecthf = "select * from reservations_info a  where a.id='" + info.getReservationsId() + "' limit 0,1";
            ReservationsInfo reservationsInfo = sqlMapper.selectOne(sqlselecthf, ReservationsInfo.class);
            if (reservationsInfo != null) {
                if (reservationsInfo.getHuifang() == null || reservationsInfo.getHuifang() == "") {
                    String updatesql = "update reservations_info a set a.huifang=CONCAT(concat(char(10),' ,<b>" + DateTimeKit.now() + "</b>[" + ShiroKit.getUser().getAccount() + "]:" + info.getRevisitContent() + "'))  where id='" + info.getReservationsId() + "'";
                    sqlMapper.update(updatesql);
                } else {
                    String updatesql = "update reservations_info a set  a.huifang=CONCAT(huifang,concat(char(10),' ,<b>" + DateTimeKit.now() + "</b>[" + ShiroKit.getUser().getAccount() + "]:" + info.getRevisitContent() + "'))  where id='" + info.getReservationsId() + "'";
                    sqlMapper.update(updatesql);
                }
            }
            String sql = "update " + this.getTableName() + " set cause_of_no_return_visit='" + info.getCauseOfNoReturnVisit() + "',is_return_visit=" + info.getIsReturnVisit() + "," +
                    "remarks_of_return_visit='" + info.getRemarksOfReturnVisit() + "',reservations='" + info.getReservations() + "',appointment_time=" + appointmentTime + ",return_to_remark='" + ShiroKit.getUser().getAccount() + "'" +
                    " where reservations_id='" + info.getReservationsId() + "'";
            return sqlMapper.update(sql);
        }
    }

    @RequestMapping(value = "/to_revisitOperation/{reservationsId}")
    public String toRevisitOperation(@PathVariable String reservationsId, Model model) throws Exception {
        if (ToolUtil.isEmpty(reservationsId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        List<AddVisitedInfo> revisitRecordList = consultantService.getRevisitRecordList(reservationsId);
        String sql = "select * from reservations_info where id='" + reservationsId + "' limit 0,1";
        model.addAttribute("reservationsId", reservationsId);
        model.addAttribute("revisitRecordList", revisitRecordList);
        ReservationsInfo reservationsInfo = sqlMapper.selectOne(sql, ReservationsInfo.class);
        if (reservationsInfo != null) {
            if (reservationsInfo.getCustomerSex() != null) {
                if (reservationsInfo.getCustomerSex() == 1) {
                    reservationsInfo.setSex("男");
                } else if (reservationsInfo.getCustomerSex() == 2) {
                    reservationsInfo.setSex("女");
                } else {
                    reservationsInfo.setSex("未知");
                }
            }
        }
        model.addAttribute("reservationsInfo", reservationsInfo);
        model.addAttribute("reservations", ShiroKit.getUser().getAccount());
        return PREFIX + "is_revisitd.html";
    }

    /**
     * 预约客户管理列表
     */
    @RequestMapping("/list")
    @ResponseBody
    public Object testrInfoList(SearchDoctorLookedInfo info, HttpServletRequest request) {
        Page<DoctorLookedInfo> page = new PageFactory<DoctorLookedInfo>().defaultPage();
        try {
            List<DoctorLookedInfo> list = service.selectPageListByQueryGetMap(page, info);
            page.setRecords(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.packForBT(page);
    }

    /**
     * 跳转到病例列表主界面
     *
     * @return
     */
    @RequestMapping(value = "/caseInfoPage/{customerId}")
    public String caseInfoPage(@PathVariable String customerId, Model model) throws Exception {
        if (ToolUtil.isEmpty(customerId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("customerId", customerId);
        return PREFIX + "caseInfoPage.html";
    }

    /**
     * 查看客户的所有病例列表(表格ajax 组件请求)
     *
     * @param customerId 客户ID
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/caseTableList/{customerId}")
    @ResponseBody
    public List<CaseInfo> caseTableList(@PathVariable String customerId, Model model) throws Exception {
        if (ToolUtil.isEmpty(customerId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String tableName1 = tableHead + "customer_info";
        String sql = "select * from case_info c," + tableName1 + " w  where  c.customer_id = w.id and customer_id = '" + customerId + "' order by c.operation_time desc; ";
        List<CaseInfo> list = sqlMapper.selectList(sql, CaseInfo.class);

        return list;
    }

    /**
     * 医生回访数据列表
     */
    @RequestMapping(value = "/FollowTableList/{customerId}")
    @ResponseBody
    public List<DoctorRevisitInfo> FollowTableList(@PathVariable String customerId, Model model) throws Exception {
        if (ToolUtil.isEmpty(customerId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String tableName1 = tableHead + "customer_info";
        String sql = "select * from return_doctor_visit_info c," + tableName1 + " w  where  c.customer_id = w.id and customer_id = '" + customerId + "'";
        List<DoctorRevisitInfo> list = sqlMapper.selectList(sql, DoctorRevisitInfo.class);
        return list;
    }


    /**
     * 跳转到添加病例界面
     *
     * @return
     */
    @RequestMapping(value = "/add/{cc}")
    public String addRecord(@PathVariable String cc, Model model) throws Exception {
        String customerId = cc.split(",")[0];
        String customerStatus = cc.split(",")[1];
        if (ToolUtil.isEmpty(customerId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();

        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String sql = " select a.id as id,a.account as doctor from user a left join  dept b on a.deptid=b.id left join role c on find_in_set(c.id,a.roleid) > 0 " +
                " where b.abbreviation='" + tableHead + "' and c.name='医生'";
        List<ConsultantInfo> list = sqlMapper.selectList(sql, ConsultantInfo.class);

        //获得该客户的就诊时间
        /*String sql1 = "select diagnose_time as diagnoseTime from doctor_diagnosis_info where customer_id = '" + customerId + "'";
        List<DoctorDiagnosisInfo> DoctorDiagnosisInfoList = sqlMapper.selectList(sql1, DoctorDiagnosisInfo.class);
        for (DoctorDiagnosisInfo info1 : DoctorDiagnosisInfoList) {
            if (info1.getDiagnoseTime() != "" && info1.getDiagnoseTime() != null) {
                info1.setDiagnoseTime(info1.getDiagnoseTime().substring(0, 19));
            }
        }*/

        String tableName = tableHead + "deal_info";
        String sql2 = "select distinct (p.pay_service_name) as payServiceName,t.pay_service_id as payServiceId from  " + tableName + "  t " +
                "left join pay_service_info p on p.id=t.pay_service_id " +
                "where customer_id = '" + customerId + "'";
        List<ReservationsInfo> reservationsInfo = sqlMapper.selectList(sql2, ReservationsInfo.class);

        String sql3 = " select a.id as id,a.account as nurse from user a left join  dept b on a.deptid=b.id left join role c on find_in_set(c.id,a.roleid) > 0 " +
                " where b.abbreviation='" + tableHead + "' and c.name='护士'";
        List<ConsultantInfo> list1 = sqlMapper.selectList(sql3, ConsultantInfo.class);

        String selectsql = "select * from " + this.getTableName() + " where id='" + customerId + "'";
        CustomerInfo customerInfo = sqlMapper.selectOne(selectsql, CustomerInfo.class);
        if (customerInfo != null) {
            model.addAttribute("reservationsId", customerInfo.getReservationsId());
        }

        //获得患者的到店时间
        String sql1 = "select arrival_time as arrivalTime from " + this.getTableName() + " " +
                "where reservations_id = '" + customerInfo.getReservationsId() + "' and arrival_time is not null ";
        List<CustomerInfo> customerList = sqlMapper.selectList(sql1, CustomerInfo.class);

        model.addAttribute("list", list);
        model.addAttribute("list1", list1);
        model.addAttribute("userName", ShiroKit.getUser().getName());
        model.addAttribute("customerList", customerList);
        model.addAttribute("customerId", customerId);
        model.addAttribute("customerStatus", customerStatus);
        model.addAttribute("reservationsId", list1.get(0).getReservationsId());
        model.addAttribute("reservationsInfo", reservationsInfo);

        return PREFIX + "medical_records.html";
    }


    /**
     * 病例数据添加
     *
     * @return
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    public int add(CaseInfo info) throws Exception {
        return service.insert(info);
    }

    /**
     * 统计查询
     */
    @RequestMapping(value = "/total", method = RequestMethod.GET)
    @ResponseBody
    public List<ConsultantInfo> change(String param1, String param2,  String customerAgeEnd,
                                       String payServiceName, String customerSex, String customerAgeStart) throws Exception {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String tableName = tableHead + "deal_info";
        String tableName1 = tableHead + "customer_info";
        String contitionInfo = "";
        if (StringUtils.isNotBlank(param1)) {
            contitionInfo += " and DATE_FORMAT(t2.arrival_time, '%Y-%m-%d') = '" + param1 + "' ";
        }
        if (StringUtils.isNotBlank(customerSex)) {
            contitionInfo += " and t2.customer_sex= '" + customerSex + "' ";
        }
        if (StringUtils.isNotBlank(customerAgeStart)) {
            contitionInfo += " and t2.customer_age >= '" + customerAgeStart + "'  ";
        }
        if (StringUtils.isNotBlank(customerAgeEnd)) {
            contitionInfo += " and t2.customer_age <= '" + customerAgeEnd + "' ";
        }
        String sql2 = "select * from user a left join role b on a.roleId=b.id where a.account='" + ShiroKit.getUser().getAccount() + "'";
        User user = sqlMapper.selectOne(sql2, User.class);
        if (user != null) {
            if ("1".equals(user.getRoleid()) || "1,".equals(user.getRoleid().substring(0, 2))) {
                contitionInfo += " ";
            } else {
                contitionInfo += " and t1.doctor = '" + ShiroKit.getUser().getAccount() + "' ";
            }
        }

        String a = " select count(1) as countNum from ( ";
        String b = " ) a ";
        String c = " and t1.deal_status='已成交' and t1.check_status='2'";
        String sql = a + "select t1.customer_id from " + tableName + " t1 left join " + tableName1 + " t2 on(t2.id=t1.customer_id) where 1=1 " + c + contitionInfo + " group by t1.customer_id " + b

                + " union all " + a + " select t1.customer_id from " + tableName + " t1 left join " + tableName1 + " t2 on(t2.id=t1.customer_id)  where t2.arrival_status ='1' " + c + contitionInfo + " group by t1.customer_id " + b

                + " union all " + a + " select t1.customer_id from " + tableName + " t1 left join " + tableName1 + " t2 on(t2.id=t1.customer_id)  where t2.arrival_status ='2' " + c + contitionInfo + " group by t1.customer_id " + b

                + " union all " + a + " select t1.customer_id from " + tableName + " t1 left join " + tableName1 + " t2 on(t2.id=t1.customer_id)  where t2.arrival_status ='3' " + c + contitionInfo + " group by t1.customer_id " + b

                + " union all " + a + " select t1.customer_id from " + tableName + " t1 left join " + tableName1 + " t2 on(t2.id=t1.customer_id)  where t2.arrival_status ='4' " + c + contitionInfo + " group by t1.customer_id " + b;
        List<ConsultantInfo> tongJiInfoList1 = sqlMapper.selectList(sql, ConsultantInfo.class);
        return tongJiInfoList1;
    }

    /**
     * 跳转到修改病例界面,前端传病例表ID
     */
    @RequestMapping(value = "/update/{cri}")
    public String update(@PathVariable String cri, Model model) throws Exception {
        String id = cri.split(",")[0];
        String customerId = cri.split(",")[1];
        String tableHead = ShiroKit.getUser().getAbbreviation();

        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        //先查询病例主表单个实体
        String tableName = "case_info";
        String sql = "select * from " + tableName + " t1 where t1.id='" + id + "' ";
        CaseInfo caseInfo = sqlMapper.selectOne(sql, CaseInfo.class);

        //然后查询牙位集合,把每种检测项的多个牙位装入到对应的牙位集合里面去
        String sql1 = "select * from tooth_site t1 where t1.case_id='" + id + "' order by id";
        List<ToothSite> toothSiteList = sqlMapper.selectList(sql1, ToothSite.class);
        for (ToothSite toothSite : toothSiteList) {
            //根据对应的牙位类型，给病例实体的对应牙位属性赋值,把每组多个牙位信息通过&&拼接成一个字符串属性传到前端
            if (toothSite.getYaType().equals("1")) {
                caseInfo.getToothSite1List().add(toothSite);
            }
            if (toothSite.getYaType().equals("2")) {
                caseInfo.getToothSite2List().add(toothSite);
            }
            if (toothSite.getYaType().equals("3")) {
                caseInfo.getToothSite3List().add(toothSite);
            }
            if (toothSite.getYaType().equals("4")) {
                caseInfo.getToothSite4List().add(toothSite);
            }
            if (toothSite.getYaType().equals("5")) {
                caseInfo.getToothSite5List().add(toothSite);
            }
        }
        String sqld = " select a.id as id,a.account as doctor from user a left join  dept b on a.deptid=b.id left join role c on find_in_set(c.id,a.roleid) > 0 " +
                " where b.abbreviation='" + tableHead + "' and c.name='医生'";
        List<ConsultantInfo> list = sqlMapper.selectList(sqld, ConsultantInfo.class);

        //项目
        String tableName1 = tableHead + "deal_info";
        String sql2 = "select distinct (p.pay_service_name) as payServiceName,t.pay_service_id as payServiceId from  " + tableName1 + "  t " +
                "left join pay_service_info p on p.id=t.pay_service_id " +
                "where customer_id = '" + customerId + "'";
        List<ReservationsInfo> reservationsInfo = sqlMapper.selectList(sql2, ReservationsInfo.class);
        model.addAttribute("reservationsInfo", reservationsInfo);
        model.addAttribute("list", list);
        model.addAttribute("caseInfo", caseInfo);
        return PREFIX + "update_record.html";
    }

    /**
     * 病例修改之后提交
     */
    @RequestMapping(value = "/update_record")
    @ResponseBody
    public int updateRecord(@Valid CaseInfo info, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        try {
            service.update(info);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 1;
    }


    /**
     * 查看病例详情
     *
     * @param id    病例ID
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/case_details/{id}")
    public String selectCaseInfoDetail(@PathVariable String id, Model model) throws Exception {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }

        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        //先查询病例主表单个实体
        String tableName = "case_info";
        String sql = "select * from " + tableName + " t1 where t1.id='" + id + "' ";
        CaseInfo caseInfo = sqlMapper.selectOne(sql, CaseInfo.class);
        caseInfo.setFinnallyTime(caseInfo.getFinnallyTime().substring(0, 19));

        //然后查询牙位集合,把每种检测项的多个牙位装入到对应的牙位集合里面去
        String sql1 = "select * from tooth_site t1 where t1.case_id='" + id + "' order by id";
        List<ToothSite> toothSiteList = sqlMapper.selectList(sql1, ToothSite.class);
        for (ToothSite toothSite : toothSiteList) {
            //根据对应的牙位类型，给病例实体的对应牙位属性赋值,把每组多个牙位信息通过&&拼接成一个字符串属性传到前端
            if (toothSite.getYaType().equals("1")) {
                caseInfo.getToothSite1List().add(toothSite);
            }
            if (toothSite.getYaType().equals("2")) {
                caseInfo.getToothSite2List().add(toothSite);
            }
            if (toothSite.getYaType().equals("3")) {
                caseInfo.getToothSite3List().add(toothSite);
            }
            if (toothSite.getYaType().equals("4")) {
                caseInfo.getToothSite4List().add(toothSite);
            }
            if (toothSite.getYaType().equals("5")) {
                caseInfo.getToothSite5List().add(toothSite);
            }
        }
        String sqld = " select a.id as id,a.account as doctor from user a left join  dept b on a.deptid=b.id left join role c on find_in_set(c.id,a.roleid) > 0 " +
                " where b.abbreviation='" + tableHead + "' and c.name='医生'";
        List<ConsultantInfo> list = sqlMapper.selectList(sqld, ConsultantInfo.class);
        model.addAttribute("list", list);
        model.addAttribute("caseInfo", caseInfo);
        return PREFIX + "case_details.html";
    }


    /**
     * 除单个病例信息(删除按钮ajax 组件请求)
     * 删
     *
     * @param id     病例ID
     * @param result
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/deleteCaseInfo/{id}")
    @ResponseBody
    public int deleteCaseInfo(@PathVariable String id, BindingResult result) throws Exception {
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();

        //删除病例对应的牙位信息
        String sql1 = "delete from tooth_site where case_id = '" + id + "'";
        sqlMapper.delete(sql1);

        //删除病例表对应ID的病例信息
        String tableName1 = tableHead + "case_info";
        String sql = "delete from " + tableName1 + " where id = '" + id + "'";

        return sqlMapper.delete(sql);
    }

    /**
     * 跳转到医生划价界面reservationsId
     *
     * @return
     */
    @RequestMapping(value = "/change_price/{reservationsId}")
    public String changePrice(@PathVariable String reservationsId, Model model) throws Exception {
        if (ToolUtil.isEmpty(reservationsId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }

        model.addAttribute("reservationsId", reservationsId);
        return PREFIX + "change_price.html";
    }

    /**
     * 该客户所有的项目列表,前台AJAX POST 请求要传递三个参数
     *
     * @return reservationsId，customerId，operationTime
     */
    @RequestMapping(value = "/changePriceTable/{reservationsId}")
    @ResponseBody
    public List<PayServiceInfo> changePriceTable(@PathVariable String reservationsId) throws Exception {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String tableName1 = tableHead + "deal_info";
        String sql = "select t1.id as id,t1.customer_id as customerId ,t1.reservations_id as reservationsId ," +
                "t1.outpatient_name as outpatientName , t1.deal_status  as dealStatus, t1.tc_name as tcName ," +
                "t1.pay_service_num as payServiceNum ,t1.service_actual_pay as serviceActualPay ," +
                "left(t1.operation_time,19) as operationTime,t1.remarks as remarks,t1.check_status as checkStatus," +
                " t1.folding_pay as foldingPay,t1.to_void_cause as toVoidCause,t1.doctor as doctor ,t1.left_up as leftUp ," +
                "t1.left_down as leftDown ,t1.right_up as rightUp ,t1.right_down as rightDown ,t1.pay_service as payService," +
                "t2.id as payServiceId,t2.department as department,t2.first_level_project as firstLevelProject,t1.arrears as arrears," +
                "t2.pay_service_name as payServiceName ,t2.pay_service_price_one as payServicePriceOne, t2.pay_service_price_two as payServicePriceTwo," +
                "t1.to_void_cause as toVoidCause ,t1.no_deal_cause as noDealCause,t3.customer_name as customerName ," +
                "t3.medical_record_number as medicalRecordNumber,t3.customer_status as customerStatus ,t3.customer_sex as customerSex ,t3.customer_phone as customerPhone,t3.customer_age as customerAge,\n" +
                "    (\n" +
                "        CASE t3.customer_sex\n" +
                "        WHEN 1 THEN\n" +
                "            '男'\n" +
                "        WHEN 2 THEN\n" +
                "            '女'\n" +
                "        ELSE\n" +
                "            '未知'\n" +
                "        END\n" +
                "    ) as sex  ,t3.arrival_store as arrivalStore," +
                "t3.field_tc as fieldTc from " + tableName1 + " t1 left join pay_service_info t2 on t1.pay_service_id=t2.id left join " + this.getTableName() + " t3 on t1.customer_id=t3.id" +
                " where t1.reservations_Id = '" + reservationsId + "' and t1.deal_status='已成交' and t1.doctor='" + ShiroKit.getUser().getAccount() + "' group by t1.operation_time,t1.reservations_id,t1.pay_service_id";
        List<PayServiceInfo> payServiceInfoList = sqlMapper.selectList(sql, PayServiceInfo.class);
        return payServiceInfoList;
    }

    /**
     * 划价改变项目的状态，根据当前开单的ID
     *
     * @return
     */
    @RequestMapping(value = "/hua_price/{id}")
    @ResponseBody
    public int updateStatus(@PathVariable String id) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String tableName = tableHead + "deal_info";
        String sql = "update " + tableName + "  set check_status ='1' where id2 = '" + id + "'";
        return sqlMapper.update(sql);
    }

    /**
     * 医生开始治疗修改患者状态
     *
     * @param customerId
     * @return
     */
    @RequestMapping(value = "/startTreatment", method = RequestMethod.POST)
    @ResponseBody
    public int startTreatment(String customerId) {
        String sql = "update " + this.getTableName() + "  set arrival_status ='3' where id = '" + customerId + "'";
        return sqlMapper.update(sql);
    }

    @RequestMapping(value = "/completionTreatment", method = RequestMethod.POST)
    @ResponseBody
    public int completionTreatment(String customerId) {
        String sql = "update " + this.getTableName() + "  set arrival_status ='4' where id = '" + customerId + "'";
        return sqlMapper.update(sql);
    }

    //回退
    @RequestMapping(value = "/returnTo", method = RequestMethod.POST)
    @ResponseBody
    public String returnTo(String customerId, Model model) {
        String sql = "update " + this.getTableName() + "  set arrival_status =arrival_status-1 where id = '" + customerId + "'";
        int a = sqlMapper.update(sql);
        String sql2 = "select * from " + this.getTableName() + " where id= '" + customerId + "'";
        ConsultantInfo customerInfo = sqlMapper.selectOne(sql2, ConsultantInfo.class);
        return a + "," + customerInfo.getArrivalStatus();
    }


    //患者取消预约
    @RequestMapping(value = "/cancelAppointment", method = RequestMethod.POST)
    @ResponseBody
    public int cancelAppointment(String customerId) {
        String sql = "delete from " + this.getTableName() + " where id = '" + customerId + "'";
        String sql1 ="select customer_name as customerName,customer_phone as customerPhone,archiving as archiving,filing_time as filingTime from "+this.getTableName()+" where id = '" + customerId + "' ";
        CustomerInfo info = sqlMapper.selectOne(sql1,CustomerInfo.class);
        String sq11 = "INSERT INTO `reservations_cance_info_log` ( `delete_people`,`delete_cname`,`delete_cphone`, `archiving`,`filing_time`, `delete_time`) VALUES " +
                " ('" + ShiroKit.getUser().getAccount() + "' ,'" + info.getCustomerName() + "','"+info.getCustomerPhone()+"', '" +info.getArchiving()+ "', '" +info.getFilingTime()+ "','"+DateTimeKit.now()+"');";
        sqlMapper.insert(sq11);
        return sqlMapper.delete(sql);
    }

    /**
     * 患者到店
     *
     * @param customerId
     * @return
     */
    @RequestMapping(value = "/regresses", method = RequestMethod.POST)
    @ResponseBody
    public int regresses(String customerId) {
        String selectsql = "select * from " + this.getTableName() + " where id='" + customerId + "'";
        CustomerInfo customerInfo = sqlMapper.selectOne(selectsql, CustomerInfo.class);
        String customerStatus = customerService.getCustomerStatus(customerInfo);
        String sql = "";
        String medicalRecordNumber = customerService.getMedicalRecordNumber();
        String selectsql1 = "select * from reservations_info a where a.id='" + customerInfo.getReservationsId() + "' limit 0,1";
        ReservationsInfo reservationsInfo = sqlMapper.selectOne(selectsql1, ReservationsInfo.class);
        if (reservationsInfo != null) {
            if ("预约".equals(reservationsInfo.getStatus())) {
                String sql1 = "update reservations_info a set a.status='到店', a.arrival_store='"+ ShiroKit.getUser().getOutpatientName() +"',a.identification_number='" + medicalRecordNumber + "',a.first_visit_date='" + DateTimeKit.now() + "' where id='" + customerInfo.getReservationsId() + "'";
                sqlMapper.update(sql1);
            }
        } else {
            customerInfo.setIdentificationNumber(medicalRecordNumber);
            reservationsService.insert(customerInfo);
        }
        if ("新客首次".equals(customerStatus)) {
            sql = "update " + this.getTableName() + "  set arrival_status ='2',phone_shar_ship='本人',medical_record_number='" + medicalRecordNumber + "',status='到店',customer_status='" + customerStatus + "'," +
                    "arrival_time='" + DateTimeKit.now() + "',first_visit_date='" + DateTimeKit.now() + "' where id = '" + customerId + "' ";
        } else {
            String sqlgetm="select * from "+ this.getTableName() + " where customer_phone='"+customerInfo.getCustomerPhone()+"' and left(arrival_time,10)<'"+DateTimeKit.now().substring(0,10)+"' limit 0,1";
            CustomerInfo customerInfo2=sqlMapper.selectOne(sqlgetm,CustomerInfo.class);
            sql = "update " + this.getTableName() + "  set arrival_status ='2',status='到店',phone_shar_ship='"+customerInfo2.getPhoneSharShip()+"',medical_record_number='" + customerInfo2.getMedicalRecordNumber() + "',status='到店',customer_status='" + customerStatus + "'," +
                    "arrival_time='" + DateTimeKit.now() + "' where id = '" + customerId + "' ";
        }
        return sqlMapper.update(sql);
    }

    /**
     * 患者离开
     *
     * @param customerId
     * @return
     */
    @RequestMapping(value = "/alreadyLeave", method = RequestMethod.POST)
    @ResponseBody
    public int alreadyLeave(String customerId) {
        String sql = "update " + this.getTableName() + "  set arrival_status ='5' where id = '" + customerId + "'";
        return sqlMapper.update(sql);
    }

    /**
     * 点击确认
     *
     * @param customerId
     * @return
     */
    @RequestMapping(value = "/sureAppointment", method = RequestMethod.POST)
    @ResponseBody
    public int sureAppointment(String customerId) {
        String sql = "update " + this.getTableName() + "  set arrival_status ='6' where id = '" + customerId + "'";
        return sqlMapper.update(sql);
    }

    /**
     * 患者离开
     *
     * @param customerId
     * @return
     */
    @RequestMapping(value = "/fallbackAction", method = RequestMethod.POST)
    @ResponseBody
    public int fallbackAction(String customerId, String arrivalStatus) {
        if (arrivalStatus.equals("5")) {
            String sql = "update " + this.getTableName() + "  set arrival_status ='4' where id = '" + customerId + "'";
            sqlMapper.update(sql);
        } else if (arrivalStatus.equals("4")) {
            String sql = "update " + this.getTableName() + "  set arrival_status ='3' where id = '" + customerId + "'";
            sqlMapper.update(sql);
        } else if (arrivalStatus.equals("3")) {
            String sql = "update " + this.getTableName() + "  set arrival_status ='2' where id = '" + customerId + "'";
            sqlMapper.update(sql);
        } else if (arrivalStatus.equals("2")) {
            String sql = "update " + this.getTableName() + "  set arrival_status ='1',arrival_time=null where id = '" + customerId + "'";
            sqlMapper.update(sql);
            String sql1 = "select reservations_id from " + this.getTableName() + " where id='" + customerId + "' limit 0,1";
            CustomerInfo customerInfo = sqlMapper.selectOne(sql1, CustomerInfo.class);
            String sql2 = "select * from reservations_info where id='" + customerInfo.getReservationsId() + "' " +
                    "and first_visit_date like '%" + (DateTimeKit.now()).substring(0, 10) + "%' and one_channel!='直接上门' and one_channel!='老带新' limit 0,1";
            ReservationsInfo reservationsInfo = sqlMapper.selectOne(sql2, ReservationsInfo.class);
            if (reservationsInfo != null) {
                String updatesql = "update reservations_info set status='预约',first_visit_date=null where id='" + customerInfo.getReservationsId() + "'";
                sqlMapper.update(updatesql);
            } else {
                String deletesql = "delete from reservations_info where id='" + customerInfo.getReservationsId() + "'";
                sqlMapper.delete(deletesql);
            }
        } else if (arrivalStatus.equals("1")) {
            String sql = "update " + this.getTableName() + "  set arrival_status ='1' where id = '" + customerId + "'";
            sqlMapper.update(sql);
        }

        return 1;
    }

    /**
     * 添加随访
     *
     * @return
     */
    @RequestMapping(value = "/addDoctorContent", method = RequestMethod.POST)
    @ResponseBody
    public int addDoctorContent(String customerId, String doctor, String revisitTime,
                                String remarks, String reservationsId, String arrivalStore) {
        String sql = "insert into return_doctor_visit_info (reservations_id,customer_id,revisit,revisit_time," +
                "outpatient_name,doctor,remarks) values ('" + reservationsId
                + "','" + customerId + "','" + doctor + "','" + revisitTime + "','" + arrivalStore
                + "','" + doctor + "','" + remarks + "')";
        return sqlMapper.insert(sql);
    }

    /**
     * 客户姓名添加随访
     */
    @RequestMapping(value = "/addDoctorContent2", method = RequestMethod.POST)
    @ResponseBody
    public int addDoctorContent2(String customerId, String doctor, String revisitContent, String revisitTime,
                                 String remarks, String reservationsId, String arrivalStore, String createName) {
        int revisitStatus = 1;
        if (!ToolUtil.isEmpty(revisitContent)) {  //随访结果不为空表示随访完成
            revisitStatus = 2;
        }
        String sql = "insert into return_doctor_visit_info (reservations_id,customer_id,revisit,revisit_time," +
                "outpatient_name,doctor,remarks,revisit_content,create_name,revisit_status) values ('" + reservationsId
                + "','" + customerId + "','" + doctor + "','" + revisitTime + "','" + arrivalStore
                + "','" + doctor + "','" + remarks + "','" + revisitContent + "','" + createName
                + "','" + revisitStatus + "')";
        return sqlMapper.insert(sql);
    }

    /**
     * 完成随访跟进随访结果
     */
    @RequestMapping(value = "/updateDoctorContent", method = RequestMethod.POST)
    @ResponseBody
    public int updateDoctorContent(String doctor, String createName,
                                   String revisitTime, String revisitContent, String doctorVisitId,
                                   String remarks, String reservationsId) {
        String sql = "update return_doctor_visit_info set doctor='" + doctor + "',create_name='" + createName
                + "',revisit_time='" + revisitTime + "',revisit_content='" + revisitContent
                + "',remarks='" + remarks + "',revisit_status=2 " +
                " where reservations_id='" + reservationsId + "' and id='" + doctorVisitId + "'";
        return sqlMapper.update(sql);
    }

    /**
     * 图片删除
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/imgDel", method = RequestMethod.POST)
    @ResponseBody
    public int imgDel(String id) {
        String sql = "delete from icon_info where id = '" + id + "'";
        return sqlMapper.delete(sql);
    }


    /**
     * 选择上传影像类型
     */
    @RequestMapping("/openIconType/{cri}")
    public String openIconType(@PathVariable String cri, Model model) {
        String reservationsId = cri.split(",")[0];
        String customerId = cri.split(",")[1];
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        //得到项目
        String tableName = tableHead + "deal_info";
        String sql2 = "select distinct (p.pay_service_name) as payServiceName,t.pay_service_id as payServiceId from  " + tableName + "  t " +
                "left join pay_service_info p on p.id=t.pay_service_id " +
                "where customer_id = '" + customerId + "' ";
        List<ReservationsInfo> reservationsInfo = sqlMapper.selectList(sql2, ReservationsInfo.class);
        model.addAttribute("reservationsInfo", reservationsInfo);

        //获得患者的到店时间
        String sql1 = "select arrival_time as arrivalTime from " + this.getTableName() + " " +
                "where reservations_id = '" + reservationsId + "' and arrival_time is not null ";
        List<CustomerInfo> customerList = sqlMapper.selectList(sql1, CustomerInfo.class);
        model.addAttribute("customerList", customerList);

        model.addAttribute("customerId", customerId);
        model.addAttribute("reservationsId", reservationsId);
        return PREFIX + "openIconType.html";
    }


    /**
     * 初诊打印病历
     */
    @RequestMapping("/doctor_print/{id}")
    public String doctor_print(@PathVariable String id, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }

        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        //先查询病例主表单个实体
        String tableName = "case_info";
        String sql = "select * from " + tableName + " t1 where t1.id='" + id + "' ";
        CaseInfo caseInfo = sqlMapper.selectOne(sql, CaseInfo.class);
        //然后查询牙位集合,把每种检测项的多个牙位装入到对应的牙位集合里面去
        String sql1 = "select * from tooth_site t1 where t1.case_id='" + id + "' order by id";
        List<ToothSite> toothSiteList = sqlMapper.selectList(sql1, ToothSite.class);
        for (ToothSite toothSite : toothSiteList) {
            //根据对应的牙位类型，给病例实体的对应牙位属性赋值,把每组多个牙位信息通过&&拼接成一个字符串属性传到前端
            if (toothSite.getYaType().equals("1")) {
                caseInfo.getToothSite1List().add(toothSite);
            }
            if (toothSite.getYaType().equals("2")) {
                caseInfo.getToothSite2List().add(toothSite);
            }
            if (toothSite.getYaType().equals("3")) {
                caseInfo.getToothSite3List().add(toothSite);
            }
            if (toothSite.getYaType().equals("4")) {
                caseInfo.getToothSite4List().add(toothSite);
            }

            if (toothSite.getYaType().equals("5")) {
                caseInfo.getToothSite5List().add(toothSite);
            }
        }
        String sqld = " select a.id as id,a.account as doctor from user a left join  dept b on a.deptid=b.id left join role c on find_in_set(c.id,a.roleid) > 0 " +
                " where b.abbreviation='" + tableHead + "' and c.name='医生'";
        List<ConsultantInfo> list = sqlMapper.selectList(sqld, ConsultantInfo.class);
        String selectSql = "select * from " + this.getTableName() + " where id='" + caseInfo.getCustomerId() + "'";
        CustomerInfo customerInfo = sqlMapper.selectOne(selectSql, CustomerInfo.class);
        if (customerInfo != null) {
            if (customerInfo.getCustomerSex() == 1) {
                customerInfo.setSex("男");
            } else if (customerInfo.getCustomerSex() == 2) {
                customerInfo.setSex("女");
            } else {
                customerInfo.setSex("未知");
            }
        }
        String sql22="select * from dept where abbreviation='"+tableHead+"'";
        Dept dept=sqlMapper.selectOne(sql22,Dept.class);

        model.addAttribute("deptInfo", dept);
        model.addAttribute("list", list);
        model.addAttribute("caseInfo", caseInfo);
        model.addAttribute("customerInfo", customerInfo);
        return PREFIX + "doctor_print.html";
    }

    /**
     * 复诊打印病历
     */
    @RequestMapping("/doctor_prints/{id}")
    public String doctor_prints(@PathVariable String id, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }

        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        //先查询病例主表单个实体
        String tableName = "case_info";
        String sql = "select * from " + tableName + " t1 where t1.id='" + id + "' ";
        CaseInfo caseInfo = sqlMapper.selectOne(sql, CaseInfo.class);
        //然后查询牙位集合,把每种检测项的多个牙位装入到对应的牙位集合里面去
        String sql1 = "select * from tooth_site t1 where t1.case_id='" + id + "' order by id";
        List<ToothSite> toothSiteList = sqlMapper.selectList(sql1, ToothSite.class);
        for (ToothSite toothSite : toothSiteList) {
            //根据对应的牙位类型，给病例实体的对应牙位属性赋值,把每组多个牙位信息通过&&拼接成一个字符串属性传到前端
            if (toothSite.getYaType().equals("1")) {
                caseInfo.getToothSite1List().add(toothSite);
            }
            if (toothSite.getYaType().equals("2")) {
                caseInfo.getToothSite2List().add(toothSite);
            }
            if (toothSite.getYaType().equals("3")) {
                caseInfo.getToothSite3List().add(toothSite);
            }
            if (toothSite.getYaType().equals("4")) {
                caseInfo.getToothSite4List().add(toothSite);
            }

            if (toothSite.getYaType().equals("5")) {
                caseInfo.getToothSite5List().add(toothSite);
            }
        }
        String sqld = " select a.id as id,a.account as doctor from user a left join  dept b on a.deptid=b.id left join role c on find_in_set(c.id,a.roleid) > 0 " +
                " where b.abbreviation='" + tableHead + "' and c.name='医生'";
        List<ConsultantInfo> list = sqlMapper.selectList(sqld, ConsultantInfo.class);
        String selectSql = "select * from " + this.getTableName() + " where id='" + caseInfo.getCustomerId() + "'";
        CustomerInfo customerInfo = sqlMapper.selectOne(selectSql, CustomerInfo.class);
        if (customerInfo != null) {
            if (customerInfo.getCustomerSex() == 1) {
                customerInfo.setSex("男");
            } else if (customerInfo.getCustomerSex() == 2) {
                customerInfo.setSex("女");
            } else {
                customerInfo.setSex("未知");
            }
        }
        String sql22="select * from dept where abbreviation='"+tableHead+"'";
        Dept dept=sqlMapper.selectOne(sql22,Dept.class);

        model.addAttribute("deptInfo", dept);
        model.addAttribute("list", list);
        model.addAttribute("caseInfo", caseInfo);
        model.addAttribute("customerInfo", customerInfo);
        return PREFIX + "doctor_prints.html";
    }


    /**
     * 初始化下拉预约时间
     */

    @RequestMapping(value = "/diagnoseList", method = RequestMethod.POST)
    @ResponseBody
    public List<DoctorDiagnosisInfo> diagnoseList(String reservationsId, String customerId, Model model) {
        //查询此人的看诊记录
        String sql = "select customer_id as customerId,reservations_id as reservationsId," +
                "outpatient_name as outpatientName,diagnose_time as diagnoseTime " +
                " from doctor_diagnosis_info where reservations_id='" + reservationsId + "'";
        List<DoctorDiagnosisInfo> doctorDiagnosisInfo = sqlMapper.selectList(sql, DoctorDiagnosisInfo.class);

        return doctorDiagnosisInfo;
    }


    /**
     * 上传图片(上传到项目的webapp/static/img)
     */
    @RequestMapping(method = RequestMethod.POST, path = "/uploadIcon/{cri}")
    @ResponseBody
    public String uploadIcon(@RequestPart("file") MultipartFile picture,
                             @PathVariable String cri) {
        String payServiceId = cri.split(",")[0];
        String customerId = cri.split(",")[1];
        String reservationsId = cri.split(",")[2];
        String iconType = cri.split(",")[3];
        String remarks = cri.split(",")[4];
        String alldiagnosetime = cri.split(",")[5];
        String alldiagnose2 = alldiagnosetime + " " + ShiroKit.getUser().getOutpatientName();
        String realPath = "D:\\20180522\\apache-tomcat-8.0.30\\webapps\\ROOT\\yingxiang";
        String httpUrl = "http://47.98.150.186/yingxiang/";
        String imageurl = httpUrl + "\\" + picture.getOriginalFilename();
        try {
            FileUtils.copyInputStreamToFile(picture.getInputStream(), new File(realPath, picture.getOriginalFilename()));

            String sql = "insert into  icon_info (customer_id,reservations_id,outpatient_name,add_name," +
                    "add_time,image_url,icon_name,remarks,diagnoseTime,pay_service_id) values ('" + customerId
                    + "','" + reservationsId + "','" + ShiroKit.getUser().getOutpatientName() + "','"
                    + ShiroKit.getUser().getAccount() + "','" + DateTimeKit.now() + "','" + imageurl
                    + "','" + iconType + "','" + remarks + "','" + alldiagnose2 + "','" + payServiceId + "')";
            sqlMapper.insert(sql);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return realPath;
    }

    /**
     * 获得影像信息
     *
     * @return
     */
    @RequestMapping(path = "/getIconInfo/{cri}", method = RequestMethod.POST)
    @ResponseBody
    public List<IconInfo> getIconInfo(@PathVariable String cri, HttpServletRequest request, Model model) {
        List<IconInfo> list = new ArrayList<>();
        String customerId = cri.split(",")[0];
        String reservationsId = cri.split(",")[1];
        String iconType = cri.split(",")[2];
        String param = "";
        if (StringUtils.isNotBlank(iconType) && !iconType.equals("所有类型")) {
            param += " and i.icon_name = '" + iconType + "' ";
        }
        if (StringUtils.isNotBlank(customerId)) {
            param += " and i.customer_id = '" + customerId + "' ";
        }
        if (StringUtils.isNotBlank(customerId)) {
            param += " and i.reservations_id = '" + reservationsId + "' ";
        }
        try {
            String sql = "  select  i.id ,i.customer_id as customerId,i.reservations_id as reservationsId,i.icon_name as iconName," +
                    "  i.outpatient_name as outpatientName,i.diagnoseTime as diagnoseTime,i.add_name as addName,i.add_time as addTime," +
                    "i.remarks as remarks,i.image_url as imageUrl,p.pay_service_name as payServiceName  from icon_info i " +
                    "left join pay_service_info p on p.id=i.pay_service_id  where 1=1 " + param;
            list = sqlMapper.selectList(sql, IconInfo.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 医生排班
     *
     * @return
     */
    @RequestMapping(value = "/findDoctorSchedulingList/", method = RequestMethod.POST)
    @ResponseBody
    public List<DoctorSchedulingInfo> findDoctorSchedulingList(String startDate, String endDate) {
        //根据角色用户查询所有医生
        String sql = "  select a.id as id,a.account as doctor from user a  left join role c on find_in_set(c.id,a.roleid) > 0 \n" +
                " left join dept b on a.deptid=b.id  where  c.name='医生'\n" +
                " and b.simplename='" + ShiroKit.getUser().getOutpatientName() + "'";
        List<ConsultantInfo> docList = sqlMapper.selectList(sql, ConsultantInfo.class);
        //根据当前日期查询 所有的排班信息
        String sql1 = "select id as id,doctor_id as doctorId,status as status ,remarks as remarks,create_time as createTime,update_people as updatePeople" +
                ",update_time as updateTime,the_date as theDate from doctor_scheduling where the_date >='" + startDate + "'and the_date <='" + endDate + "' ";

        List<DoctorSchedulingInfo> schList = sqlMapper.selectList(sql1, DoctorSchedulingInfo.class);

        //循环医生集合，组装每个医生周一至周日的排班情况，默认是正常班，通过查询医生排班表已设置的休息记录给对应医生对应的日期赋值对应的排班状态
        List<DoctorSchedulingInfo> tableList = new ArrayList<DoctorSchedulingInfo>();
        for (ConsultantInfo doc : docList) {
            //实例化一个医生对应的一周排班实体对象
            DoctorSchedulingInfo docSch = new DoctorSchedulingInfo();
            docSch.setDoctorId(doc.getId());
            docSch.setDoctorName(doc.getDoctor());

            //获取起始日期的每天的集合，比方说起点是1号，那么我们就要把1号到7号所有日期都列出来，然后循环排班班是否在对应的日期有休息的排班
            List<String> dateList = DateUtil.getDays(startDate, endDate);
            for (int i = 0; i < 7; i++) {
                String curDate = dateList.get(i);
                boolean isSch = false;//默认未休息
                //循环医生排班集合，判断对应日期是否有排班
                for (DoctorSchedulingInfo sch : schList) {
                    if (sch.getDoctorId().equals(doc.getId()) && sch.getTheDate().equals(curDate) && sch.getStatus().toString().equals("2")) {
                        isSch = true;//如果当前医生对应日期有排班，且状态为2 休息 就退出当前排班循环
                        break;
                    }
                }
                if (isSch) {//如果是排班休息
                    if (i == 0) {///周一
                        docSch.setMondayStatus("2");
                    } else if (i == 1) {///周二
                        docSch.setTuesdayStatus("2");
                    } else if (i == 2) {///周三
                        docSch.setWednesdayStatus("2");
                    } else if (i == 3) {///周四
                        docSch.setThursdayStatus("2");
                    } else if (i == 4) {///周五
                        docSch.setFridayStatus("2");
                    } else if (i == 5) {///周六
                        docSch.setSaturdayStatus("2");
                    } else if (i == 6) {///周日
                        docSch.setSundayStatus("2");
                    }
                }
            }
            //加入到返回前端集合中
            tableList.add(docSch);
        }
        return tableList;
    }

    /**
     * 修改医生排班信息(点击正常班 休息)
     */
    @RequestMapping(value = "/updateStatus/", method = RequestMethod.POST)
    @ResponseBody
    public int updateDoctorStatus(String doctorId, String docTime, String docStatus) {
        String[] times = docTime.split(",");//适配一个或者多个时间，如果只穿了1个times数组就是一个
        for (String curTime : times) {
            String sql2 = "delete  from doctor_scheduling where doctor_id = '" + doctorId + "' and the_date = '" + curTime + "'";
            sqlMapper.delete(sql2);
            String sql = " insert into doctor_scheduling (doctor_id,the_date,status,update_time,update_people) VALUES ('" + doctorId + "','" + curTime + "','" + docStatus + "','" + DateTimeKit.now() + "','" + ShiroKit.getUser().getAccount() + "')";
            sqlMapper.insert(sql);
        }
        return 1;
    }


    /**
     * 预约视图  医生集合 接口 （起始时间  和  结束时间 ）
     */
    @RequestMapping(value = "/getListed/{timeSlot}")
    @ResponseBody
    public List<ConsultantInfo> getListed(@PathVariable String timeSlot) {
        String startTime = timeSlot.split(",")[0].substring(0, 11);
        String endTime = timeSlot.split(",")[1].substring(0, 11);
        //根据角色用户查询所有医生
        String sql = "  select a.id as id,a.account as doctor from user a left join role c on find_in_set(c.id,a.roleid) > 0 \n" +
                " left join dept b on a.deptid=b.id  left join doctor_scheduling ds on ds.doctor_id = a.id  where  c.name='医生'\n" +
                " and b.simplename='" + ShiroKit.getUser().getOutpatientName() + "' and a.id not in (select ds.doctor_id from doctor_scheduling ds where ds.status = 2" +
                " and ds.the_date>='" + startTime + "' and ds.the_date<='" + endTime + "')";
        String selectsql = "select id from user where account='未指定医生'";
        User user = sqlMapper.selectOne(selectsql, User.class);
        sql += " union all (select '" + user.getId() + "' as id,'未指定医生' as doctor from user d limit 0,1)";
        List<ConsultantInfo> docList = sqlMapper.selectList(sql, ConsultantInfo.class);
        return docList;
    }

//    /**
//     * 预约视图 获取数据源   默认传了一个当前时间  前端要传开始时间  和 结束时间
//     * @return
//     */
//    @RequestMapping(value = "/getDataList/{timeSlot}", method = RequestMethod.POST)
//    @ResponseBody
//    public List<ReservationViewInfo> getReservationViewInfo(@PathVariable String timeSlot) {
//        String startTime = timeSlot.split(",")[0].substring(0,11);
//        String endTime = timeSlot.split(",")[1].substring(0,11);
//        String tableHead = ShiroKit.getUser().getAbbreviation();
//        String tableName1 = tableHead +"deal_info";
//        String tableName2 = tableHead +"customer_info";
//        //查询所有的预约数据
//        String sql = " select p.pay_service_name as serviceName,u.id as doctorId,u.name as doctorName,c.id as customerId,r.customer_name as customerName," +
//                "r.status as status,r.id as reservationsId,r.appointment_arrival_time as sTime, date_sub(r.appointment_arrival_time, interval -1 hour) eTime \n" +
//                "from  "+ tableName1 +" d left join "+ tableName2 +" c on d.customer_id = c.id \n" +
//                "left join reservations_info r on r.id = d.reservations_id\n" +
//                "left join pay_service_info p on d.pay_service_id = p.id\n" +
//                "left join user u on u.name = d.doctor\n" +
//                "where r.appointment_arrival_time >='"+ startTime +"' and r.appointment_arrival_time >= '"+ endTime+"'; ";
//        List<ReservationViewInfo> docList = sqlMapper.selectList(sql, ReservationViewInfo.class);
//        return docList;
//    }

    /**
     * 查找数据源
     */
    @RequestMapping(value = "/getDataList/{timeSlot}")
    @ResponseBody
    public List<ConsultantInfo> getDataList(@PathVariable String timeSlot) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String tableName = tableHead + "customer_info";
        String startTime = timeSlot.split(",")[0].substring(0, 10);
        String endTime = timeSlot.split(",")[1].substring(0, 10);
        String startTime2 = timeSlot.split(",")[0];
        String endTime2 = timeSlot.split(",")[1];
        String sql1 = "";
        if (startTime.equals(endTime)) {
            sql1 += "t.start_time  like CONCAT('%" + startTime + "%')";
        } else {
            sql1 += "t.start_time >=  '" + startTime2 + "' and t.end_time <= '" + endTime2 + "'";
        }
        //根据角色用户查询所有医生
        String sql = " select * from (select t1.id as id,t.customer_name as customerName,customer_status as customerStatus,t.customer_age as customerAge,t.customer_phone as customerPhone,t.medical_record_number as medicalRecordNumber," +
                "     (\n" +
                "        CASE t.customer_sex\n" +
                "        WHEN 1 THEN\n" +
                "            '男'\n" +
                "        WHEN 2 THEN\n" +
                "            '女'\n" +
                "        ELSE\n" +
                "            '未知'\n" +
                "        END\n" +
                "    ) as sex ,t.archiving as archiving ,t.reservations_id as reservationsId,t.yellow_number as yellowNumber,t.account_arrears as accountArrears,t.arrival_status as arrivalStatus,t.arrival_store as arrivalStore ,t.birthday as birthday ," +
                "left(t.create_appointment_time,19) as createAppointmentTime,t.remarks as remarks, t.field_tc as fieldTc,t.first_visit_date as firstVisitDate," +
                "t.appointment_pay_service as appointmentPayService ,t.start_time as startTime, t.end_time as endTime,t.doctor,t.id as customerId from " + tableName + " t\n" +
                "left join user t1 on t.doctor=t1.account where " + sql1+"  order by t.create_appointment_time) t2 ";

        List<ConsultantInfo> DataList = sqlMapper.selectList(sql, ConsultantInfo.class);
        return DataList;
    }


    /**
     * 当前登录医生查找数据源
     */
    @RequestMapping(value = "/getDataListByDoctor/{timeSlot}")
    @ResponseBody
    public List<ConsultantInfo> getDataListByDoctor(@PathVariable String timeSlot) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String tableName = tableHead + "customer_info";
        String startTime = timeSlot.split(",")[0].substring(0, 11);
        String endTime = timeSlot.split(",")[1].substring(0, 11);
        String doctor = timeSlot.split(",")[2];
        //根据角色用户查询所有医生
        String sql = " select t1.id as id,t.customer_name as customerName,t.customer_age as customerAge,customer_status as customerStatus,t.customer_phone as customerPhone,t.medical_record_number as medicalRecordNumber," +
                " (\n" +
                "        CASE t.customer_sex\n" +
                "        WHEN 1 THEN\n" +
                "            '男'\n" +
                "        WHEN 2 THEN\n" +
                "            '女'\n" +
                "        ELSE\n" +
                "            '未知'\n" +
                "        END\n" +
                "    ) as sex,t.archiving as archiving ,t.reservations_id as reservationsId,t.arrival_status as arrivalStatus ,t.arrival_store as arrivalStore ,t.birthday as birthday ,left(t.create_appointment_time,19) as createAppointmentTime,t.field_tc as fieldTc,t.first_visit_date as firstVisitDate,t.appointment_pay_service as appointmentPayService ,t.start_time as startTime, t.end_time as endTime,t.doctor,t.id as customerId from " + tableName + " t\n" +
                "left join user t1 on t.doctor=t1.account where t.start_time  like CONCAT('%','" + startTime + "','%')" +
                " and doctor='" + doctor + "'";
        List<ConsultantInfo> DataList = sqlMapper.selectList(sql, ConsultantInfo.class);
        return DataList;
    }

    /**
     * 当前个人医生视图查找数据源  传开始时间和结束时间(一周时间)  医生ID
     */
    @RequestMapping(value = "/getDataDoctor/{timeSlot}")
    @ResponseBody
    public List<ConsultantInfo> getDataDoctor(@PathVariable String timeSlot) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String tableName = tableHead + "customer_info";
        String startTime = timeSlot.split(",")[0].substring(0, 11);
        String endTime = timeSlot.split(",")[1].substring(0, 11);
        String doctorId = timeSlot.split(",")[2];
        String startTime2 = timeSlot.split(",")[0];
        String endTime2 = timeSlot.split(",")[1];
        String sql1 = "";
        if (startTime.equals(endTime)) {
            sql1 += "t.start_time  like CONCAT('%" + startTime + "%')";
        } else {
            sql1 += "t.start_time >=  '" + startTime2 + "' and t.end_time <= '" + endTime2 + "'";
        }
        String sql2 = "select id,account from user where id ='" + doctorId + "'";
        User user = sqlMapper.selectOne(sql2, User.class);
        String sql = " select t1.id as id,t.customer_name as customerName,t.customer_age as customerAge,t.customer_phone as customerPhone,t.medical_record_number as medicalRecordNumber," +
                " (\n" +
                "        CASE t.customer_sex\n" +
                "        WHEN 1 THEN\n" +
                "            '男'\n" +
                "        WHEN 2 THEN\n" +
                "            '女'\n" +
                "        ELSE\n" +
                "            '未知'\n" +
                "        END\n" +
                "    ) as sex,t.archiving as archiving ,t.reservations_id as reservationsId,t.arrival_status as arrivalStatus ,t.arrival_store as arrivalStore ,t.birthday as birthday ,left(t.create_appointment_time,19) as createAppointmentTime,t.field_tc as fieldTc,t.first_visit_date as firstVisitDate,t.appointment_pay_service as appointmentPayService ,t.start_time as startTime, t.end_time as endTime,t.doctor,t.id as customerId from " + tableName + " t\n" +
                " left join user t1 on t.doctor=t1.account where " + sql1 + " and doctor='" + user.getAccount() + "'";
        List<ConsultantInfo> DataWeekList = sqlMapper.selectList(sql, ConsultantInfo.class);
        return DataWeekList;
    }

    /**
     * 当前个人医生视图查找数据源  传开始时间和结束时间(一天时间)  医生ID
     */
    @RequestMapping(value = "/getOneDoctor/{timeSlot}")
    @ResponseBody
    public List<ConsultantInfo> getOneDoctor(@PathVariable String timeSlot) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String tableName = tableHead + "customer_info";
        String startTime = timeSlot.split(",")[0].substring(0, 11);
        String endTime = timeSlot.split(",")[1].substring(0, 11);
        String doctorId = timeSlot.split(",")[2];
        String sql1 = "";
        if (startTime.equals(endTime)) {
            sql1 += "t.start_time  like CONCAT('%" + startTime + "%')";
        }
        String sql2 = "select id,account from user where id ='" + doctorId + "'";
        User user = sqlMapper.selectOne(sql2, User.class);
        String sql = " select t1.id as id,t.customer_name as customerName,t.customer_age as customerAge,t.customer_phone as customerPhone,t.medical_record_number as medicalRecordNumber," +
                " (\n" +
                "        CASE t.customer_sex\n" +
                "        WHEN 1 THEN\n" +
                "            '男'\n" +
                "        WHEN 2 THEN\n" +
                "            '女'\n" +
                "        ELSE\n" +
                "            '未知'\n" +
                "        END\n" +
                "    ) as sex,t.archiving as archiving ,t.arrival_status as arrivalStatus ,t.arrival_store as arrivalStore ,t.birthday as birthday ,left(t.create_appointment_time,19) as createAppointmentTime,t.field_tc as fieldTc,t.first_visit_date as firstVisitDate,t.appointment_pay_service as appointmentPayService ,t.start_time as startTime, t.end_time as endTime,t.doctor,t.id as customerId from " + tableName + " t\n" +
                " left join user t1 on t.doctor=t1.account where " + sql1 + " and doctor='" + user.getAccount() + "'";
        List<ConsultantInfo> DataOneList = sqlMapper.selectList(sql, ConsultantInfo.class);
        return DataOneList;
    }

    //前台预约拖拽修改
    @RequestMapping(value = "/draftingUpdate/{cri}")
    @ResponseBody
    public int draftingUpdate(@PathVariable String cri) {
        String startTime = cri.split(",")[0];
        String endTime = cri.split(",")[1];
        String doctorId = cri.split(",")[2];
        String customerId = cri.split(",")[3];
        String sql = " update " + this.getTableName() + " set start_time='" + startTime + "',end_time='"
                + endTime + "',doctor=(select account from user where id='" + doctorId + "') where id='" + customerId + "'";
        return sqlMapper.update(sql);
    }

    public String getTableName() {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String tableName = tableHead + "customer_info";
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        return tableName;
    }
}
